<template>
	<cl-page status-bar-background="transparent" :fullscreen="false">
		<view class="home" :style="isIos?'':''">
			<view class="box-shadow" style="">
				<uv-textarea :height="100" border="none" :showConfirmBar="false" count :textStyle="'font-size:40rpx;'"
					v-model="audioManagerObj.musicValue" @input="textareaInput" :formatter="formatter"
					placeholder="点八卦图输入象数，白色阳鱼输入'0'，黑色阴鱼输入' · '，输入完成后点屏幕下方播放按钮"></uv-textarea>
			</view>
			<view class="box-shadow" style="margin-top: 30rpx;">
				<gossip @changeNumber="changeNumber" :isPlay="audioManagerObj.isPlay" />
				<view class="view-button">
					<view class="view-title">
						<template v-if="musicTitle">
							{{musicTitle}}
						</template>
						<template v-else>
							暂无播放
						</template>
					</view>
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="action">
				<!-- <view class="action-item" @click="jumpRecipe">
					<uv-icon size="50rpx" name="../../static/icon/home-audio.png" color="#1d1b1f"></uv-icon>
					<text>参考方</text>
				</view> -->
				<view class="action-item" @tap="router.push('/pages/user/select-audio')">
					<uv-icon size="50rpx" custom-prefix="cl-iconfont" name="tiaoxingtu" :color="setting_status?'#1F8258':'#1d1b1f'"></uv-icon>
					<text>背景音频</text>
				</view>
				<view class="action-item" @click="showAnswering">
					<uv-icon size="50rpx" name="lianjie1" custom-prefix="cl-iconfont" color="#1d1b1f"></uv-icon>
					<text>自助配方</text>
				</view>
				<!-- <view class="action-item" @click="changeSexual">
					<uv-icon size="50rpx" :name="audioManagerObj.sexual == 'nan' ? 'account' : 'server-man'"
						color="#1d1b1f"></uv-icon>
					<text>{{ audioManagerObj.sexual == 'nan' ? '男为阳' : '女为阴' }}</text>
				</view> -->
				<view class="action-item">
					<uv-icon size="120rpx"
						:color="user?.info?.adNumber==0||user?.info?.adViewing==1?'#1F8258':'#2b2e3d'" @click="play"
						:name="audioManagerObj.isPlay ? 'pause-circle-fill' : 'play-circle-fill'"></uv-icon>
				</view>
				<!-- @click="showTime" -->
				<view class="action-item" @click="showAction">
					<uv-icon size="50rpx" name="xuanxiang-heng" custom-prefix="cl-iconfont" color="#1d1b1f"></uv-icon>
					<!-- #ifdef MP-WEIXIN -->
					<text>更多功能</text>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<text v-if="isRegular">
						<uv-count-down :time="regularNumberTime" format="HH:mm:ss" @finish="countDown"></uv-count-down>
					</text>
					<text v-else>更多功能</text>
					<!-- #endif -->
				</view>
				<view class="action-item" @click="showHistory">
					<uv-icon size="50rpx" name="mianbaoxie" custom-prefix="cl-iconfont" color="#1d1b1f"></uv-icon>
					<text>播放记录</text>
				</view>
			</view>
		</view>
		<!-- 更多功能弹框 -->
		<uv-popup ref="actionPopup" mode="bottom" :safeAreaInsetBottom="false" round="20" bgColor="none">
			<view class="actionPopup-content">
				<view class="action-item" @click="showTime">
					<uv-icon size="50rpx" custom-prefix="cl-iconfont" name="shijian" color="#1d1b1f"></uv-icon>
					<!-- #ifdef MP-WEIXIN -->
					<text>定时</text>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<text v-if="isRegular">
						<uv-count-down :time="regularNumberTime" format="HH:mm:ss" @finish="countDown"></uv-count-down>
					</text>
					<text v-else>定时</text>
					<!-- #endif -->
				</view>
				<view class="action-item" @click="showSpeed">
					<uv-icon size="50rpx" custom-prefix="cl-iconfont" name="jiantou-youhua" color="#1d1b1f"></uv-icon>
					<text>倍速</text>
				</view>
				<view class="action-item" @click="changeSexual">
					<uv-icon size="50rpx" custom-prefix="cl-iconfont"
						:name="audioManagerObj.sexual == 'nan' ? 'yonghu' : 'qunzu'" color="#1d1b1f"></uv-icon>
					<text>{{ audioManagerObj.sexual == 'nan' ? '男为阳' : '女为阴' }}</text>
				</view>
			</view>
		</uv-popup>
		<!-- 定时弹框 -->
		<uv-popup ref="timePopup" mode="right" round="20" bgColor="none">
			<view class="timePopup-content">
				<view class="timePopup-content-list line" v-for="(item, index) in regularTimeList" :key="index"
					@click="selectRegularTime(item)">
					<view class="timePopup-content-list-title">
						{{ item.title }}
						<view class="timePopup-content-list-time"
							v-if="regularTimeCurrent == item.value && regularNumberTime > 0">
							<uv-count-down :time="regularNumberTime" format="HH:mm:ss"></uv-count-down>
						</view>
					</view>
					<view>
						<uv-icon size="30rpx"
							:name="regularTimeCurrent == item.value ? 'checkmark-circle-fill' : 'checkmark-circle'"
							:color="regularTimeCurrent == item.value ? '#1F8258' : '#1d1b1f'"></uv-icon>
					</view>
				</view>
				<view class="timePopup-content-list" @click="showcustomTime">
					<view class="timePopup-content-list-title">
						自定义
						<view class="timePopup-content-list-time"
							v-if="regularTimeCurrent == 999 && regularNumberTime > 0">
							<uv-count-down :time="regularNumberTime" format="HH:mm:ss"></uv-count-down>
						</view>
					</view>
				</view>
			</view>
		</uv-popup>
		<!-- 倍速 -->
		<uv-popup ref="speedPopup" mode="bottom" round="20" bgColor="none">
			<view class="speedPopup-content">
				<view class="historyPopup-content-title">
					调整倍速
				</view>
				<view class="speedPopup-speed">
					<cl-slider :active-color="'#1F8258'" @change="changeSlider" v-model="audioManagerObj.speed"
						:step="0.1" show-value :min="0.5" :max="2"></cl-slider>
				</view>
			</view>
		</uv-popup>
		<!-- 播放记录 -->
		<uv-popup ref="historyPopup" @change="historyPopupChange" mode="bottom" round="10" bgColor="none"
			:safeAreaInsetBottom="false">
			<view class="historyPopup-content" style="overflow-y: auto;">
				<view class="historyPopup-content-title" style="position: sticky;top:0rpx;left:0;right:0;">
					当前播放列表 <text>({{recordList.length}})</text>
				</view>
				<scroll-view scroll-y enable-flex class="scroller" :scroll-into-view="view" scroll-with-animation
					enable-back-to-top style="padding:0 20rpx;width:100%;box-sizing: border-box;">
					<view class="historyPopup-content-list uv-border-bottom" v-for="(item,index) in recordList"
						:key="index" :id="`group-${item.id}`">
						<view class="" style="flex:1;margin-right:40rpx" @click="playRecordList(item)">
							<view class="timePopup-content-list-title"
								:class="audioManagerObj.playId==item.id?'historyPopup-current':''">
								<text
									:class="item.name?'small-size':''">{{item.name?item.name:item.elephantNumber}}</text>
							</view>
							<view class="timePopup-content-list-title"
								:class="audioManagerObj.playId==item.id?'historyPopup-current':''">
								<text :class="item.name?'small-size-1':''">{{item.name?item.elephantNumber:''}}</text>
							</view>
						</view>
						<view style="margin-right:40rpx"
							@tap="router.push('/pages/index/edit?id='+item.id+'&elephantNumber='+item.elephantNumber)">
							<uv-icon size="40rpx" name="edit-pen" color="#1d1b1f"></uv-icon>
						</view>
						<view @click="deleteRecord(item,index)" v-if="audioManagerObj.playId!=item.id">
							<uv-icon size="40rpx" name="close" color="#1d1b1f"></uv-icon>
						</view>
					</view>
				</scroll-view>
				<view class="historyPopup-empty">
					<uv-empty :text="'暂无播放记录'" :textSize="16" icon="https://cdn.uviewui.com/uview/empty/data.png"
						v-if="recordList.length==0"></uv-empty>
				</view>
			</view>
		</uv-popup>
		<!-- 自定义时间弹框 -->
		<uv-datetime-picker ref="datetimePicker" :formatter="timeFormatter" @cancel="datetimeClose"
			v-model="regularTime" mode="time" @confirm="datetimeConfirm" />
		<!-- 热更新 -->
		<appUpdate />
		<!-- <Tabbar /> -->
	</cl-page>
</template>

<script lang="ts" setup>
	import { useApp, useCool, useStore } from "/@/cool";
	import { isIos, storage, tencentUrl, changeSlider, audioManagerObj, playMusic, getNetworkType, clearAudioManager, setMusicValueArr, stopAudioManager } from "/@/cool/utils";
	import { useUi } from "/$/cool-ui";
	import gossip from "./components/gossip.vue";
	import appUpdate from "/@/components/app-update.vue"
	import { ref, computed, } from "vue";
	import { onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
	import Tabbar from "./components/tabbar.vue";
	const { router, service } = useCool();
	const ui = useUi();
	const { user } = useStore();
	const datetimePicker = ref() //自定义时间弹框
	const historyPopup = ref() //播放记录
	const timePopup = ref() //定时弹框
	const regularTimeCurrent = ref(0) //当前选中的定时时间下标
	const recipeInfo = ref({})
	const regularTimeList = ref([
		{
			title: "不定时",
			value: 0
		},
		{
			title: "15分钟",
			value: 15
		},
		{
			title: "30分钟",
			value: 30
		},
		{
			title: "60分钟",
			value: 60
		},
		{
			title: "90分钟",
			value: 90
		}
	]) //默认的定时选择列表
	const info = ref({})
	const setting_status = ref(false)
	const view = ref("")
	const setInputs = ref()
	const speedPopup = ref() //倍速弹框
	const actionPopup = ref() //更多功能弹框
	const historyShow = ref(false) //是否显示播放记录
	const regularTime = ref('01:00') //剩余时间
	const regularNumberTime = ref(0) //剩余时间
	const isRegular = ref(false) //是否定时
	const recordList = ref([]) //播放列表
	// 象数配方页
	function jumpRecipe() {
		router.push("/pages/index/recipe");
	}
	// 显示播放记录弹框
	async function showHistory() {
		if (await getNetworkType()) {
			getRecordPage()
			historyPopup._value.open()
		} else {
			ui.showToast("无网络，请检查网络是否连接");
		}
	}
	// 显示自定义时间弹框
	function showcustomTime() {
		datetimePicker._value.open()
	}
	function showAnswering() {
		uni.navigateToMiniProgram({
			appId: 'wx4c6401744b734596',
			path: 'pages/index/index?shareId=802ed87c995c968aed3692a1d0c1740fcdb21313ba385bd4e9628fc06550654a',
			success(res) {
				// 打开成功
			}
		})
	}
	// 点击八卦图
	function changeNumber(number : string) {
		if (audioManagerObj.musicValue == "") {
			clearAudioManager()
		}
		audioManagerObj.musicValue += number
	}
	async function textareaInput(event : any) {
		audioManagerObj.musicValue = event
	}
	function changeRecord(item, index) {
		recipeInfo.value = item
		setInputs.value.open()
	}
	async function play() {
		await playMusic()
		if (audioManagerObj.isPlay == true) {
			if (await getNetworkType()) {
				getRecordPage()
			}
		}
	}
	// 选择定时时间
	function selectRegularTime(item : { value : number; }) {
		if (item.value == 0) {
			isRegular.value = false
			regularNumberTime.value = 0
		} else {
			isRegular.value = true
			regularNumberTime.value = Number(item.value * 1000 * 60)
		}
		regularTimeCurrent.value = item.value
	}
	function historyPopupChange(res : { show : any; }) {
		if (res.show && audioManagerObj.recordId) {
			view.value = `group-${audioManagerObj.recordId}`
		}
		historyShow.value = res.show
	}
	// 打开倍速弹框
	function showSpeed() {
		speedPopup.value.open()
	}
	function closeSpeed() {
		speedPopup.value.close()
	}
	// 打开更多弹框
	function showAction() {
		actionPopup.value.open()
	}
	function closeAction() {
		actionPopup.value.close()
	}
	// 过滤数据
	function formatter(value : string) {
		// 让输入框只能输入数值，过滤其他字符
		return value.replace(/[^0-8|\·\.]/ig, "")
	}
	// 计算标题
	const musicTitle = computed(() => {
		// #ifdef APP
		return audioManagerObj.musicValueArr.slice(0, -1).join("")
		// #endif
		// #ifdef MP-WEIXIN
		return audioManagerObj.preValue ? audioManagerObj.preValue : audioManagerObj.musicValue
		// #endif
	});
	// 自定义时间选择
	function datetimeConfirm(res : { value : string; }) {
		regularTime.value = res.value
		let timers = MakeDurationToSeconds(res.value)
		regularNumberTime.value = Number(timers * 1000 * 60);
		datetimePicker.value.close()
		isRegular.value = true
		regularTimeCurrent.value = 999
	}
	// 自定义时间关闭
	function datetimeClose() {
		datetimePicker.value.close()
		regularTime.value = "01:00"
	}
	// 返回多少分钟
	function MakeDurationToSeconds(time : string) {
		let str = time.split(":")
		let min = parseInt(str[0] * 60)
		let ss = parseInt(str[1])
		let timers = min + ss
		return timers
	}
	// 开启定时弹出层
	function showTime() {
		timePopup.value.open()
	}
	onShareAppMessage(() => {
		return {
			path: "/pages/index/index",
			title: "借天地能量，助身心健康！象数疗法有缘人共享~",
			imageUrl: "https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/common_option/wechat_option/share.jpg"
		}
	})
	onShareTimeline(() => {
		return {
			path: "/pages/index/index",
			title: "借天地能量，助身心健康！象数疗法有缘人共享~",
			imageUrl: "https://image-apk-1310343798.cos.ap-nanjing.myqcloud.com/common_option/wechat_option/share.jpg"
		}
	})
	// 倒计时结束
	function countDown() {
		isRegular.value = false
		stopAudioManager()
		datetimeClose()
		// 防止空白音频的定时器没有清理干净
		setTimeout(() => {
			isRegular.value = false
			stopAudioManager()
			datetimeClose()
		}, 1500)
	}
	function timeFormatter(type : string, value : any) {
		if (type === 'hour') {
			return `${value}小时`
		}
		if (type === 'minute') {
			return `${value}分钟`
		}
		return value
	}
	// 切换男女
	function changeSexual() {
		if (audioManagerObj.sexual == 'nan') {
			audioManagerObj.sexual = "nv"
			ui.showToast("女为阴");
		} else {
			audioManagerObj.sexual = "nan"
			ui.showToast("男为阳");
		}
		storage.set('sexual', audioManagerObj.sexual)
	}
	// 播放播放列表里的数据
	function playRecordList(item : { id : string; recipeName : string; elephantNumber : string; }) {
		setMusicValueArr(item.elephantNumber + '')
		audioManagerObj.playId = item.id
		historyPopup.value.close()
	}
	function deleteRecord(item : { id : any; }, index : any) {
		historyPopup.value.close()
		ui.showConfirm({
			title: "提示",
			message: "确定要删除吗",
			showCancelButton: true,
			confirmButtonText: "确定",
			callback(action) {
				if (action == "confirm") {
					service.broadcast.record.delete({ ids: [item.id] }).then(() => {
						recordList.value.splice(index, 1)
						ui.showToast({ message: "删除成功", position: "top" });
						historyPopup.value.open()
					})
				} else {
					historyPopup.value.open()
				}
			}
		});
	}
	// 获取播放列表(取前20条)
	function getRecordPage() {
		return service.broadcast.record.page({
			"page": 1,
			"size": 20,
			"order": "updateTime",
			"sort": "desc"
		}).then((res : { list : any; pagination : any }) => {
			recordList.value = res.list
			if (res.pagination.total > 0) {
				if (audioManagerObj.musicValueArr.length == 0 && audioManagerObj.isPlay == false) {
					audioManagerObj.musicValueArr = [...recordList.value[0].elephantNumber]
					audioManagerObj.musicValueArr.push("·")
					// #ifdef MP-WEIXIN
					// audioManagerObj.musicValue=recordList.value[0].elephantNumber
					// audioManagerObj.playId=recordList.value[0].id
					// #endif

				}
			}
		})
	}
	async function getSettingDetail() {
		await service.user.setting.settingUserInfo().then(res => {
			if (res) {
				if (res.settingSwitch == 1) {
					if (res.playMode == 1 ||(res.playMode == 0&& res.audioId)) {
						setting_status.value = true
					}else{
						setting_status.value = false
					}
				}else{
					setting_status.value = false
				}
			}
		})
	}
	onShow(async () => {
		console.log(11111)
		// 如果有网络，就获取播放列表
		if (await getNetworkType()) {
			if (user.token) {
				getRecordPage()
				getSettingDetail()
			}
		}
	})
</script>

<style lang="scss" scoped>
	.speedPopup-content {
		box-sizing: border-box;
		background: #fff;
		display: flex;
		flex-wrap: wrap;
		padding: 40rpx;
		display: flex;
		flex-direction: column;

		.speedPopup-speed {
			flex: 1;
			margin-top: 20rpx;
		}
	}

	.actionPopup-content {
		box-sizing: border-box;
		background: #fff;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		padding: 40rpx 0rpx 40rpx 40rpx;

		.action-item {
			padding: 20rpx;
			margin-right: 40rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}
	}

	.historyPopup-current {
		color: $cl-color-imagePlayer-primary !important;
	}

	.historyPopup-content {
		box-sizing: border-box;
		// padding: 20rpx;
		background: #fff;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		height: 70vh;
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.historyPopup-empty {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.historyPopup-content-title {
			font-weight: 700;
			border-radius: 20rpx 20rpx 0 0;
			// margin-bottom: 20rpx;
			padding: 30rpx 20rpx 10rpx;
			background: #fff;
			z-index: 9;

			text {
				font-size: $cl-font-size-sm;
				color: $cl-color-info;
			}
		}

		.historyPopup-content-list {
			padding: 20rpx 0 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.timePopup-content-list-title {
				margin-right: 40rpx;
				flex: 1;
				line-height: 1;
				word-break: break-all;
				font-size: $cl-font-size-title;
			}

			.small-size {
				font-size: $cl-font-size-lg;
				line-height: 1.2;
			}

			.small-size-1 {
				font-size: $cl-font-size-base !important;
				color: $cl-color-info !important;
			}
		}
	}

	// .line {
	// 	position: relative;
	// }

	// .line::before {
	// 	content: '';
	// 	width: 100%;
	// 	height: 1px;
	// 	position: absolute;
	// 	left: 0;
	// 	bottom: 0;
	// 	transform: scaleY(0.5);
	// 	background-color: $cl-border-color;
	// }

	.timePopup-content {
		width: 80vw;
		background: #fff;
		min-height: 100vh;
		box-sizing: border-box;
		padding: 20rpx;

		.timePopup-content-list {
			padding: 20rpx 0 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.timePopup-content-list-title {
				color: $cl-color-title;
				font-size: $cl-font-size-lg;
				display: flex;
				align-items: flex-end;

				.timePopup-content-list-time {
					margin-left: 10rpx;
				}
			}
		}
	}

	.box-shadow {
		box-shadow: 0rpx 2rpx 12rpx 0rpx rgba(0, 0, 0, 0.08);
		border-radius: 20rpx;
	}

	.timePopup {
		padding: 20rpx;
		height: 600rpx;

		.timePopup-header {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.timePopup-header-title {
				font-weight: 700;
			}
		}
	}

	.view-title {
		font-size: $cl-font-size-title;
		min-height: 100rpx;
		max-height: 300rpx;
		overflow-y: auto;
		// line-height: 80rpx;
		padding: 20rpx 40rpx;
		box-sizing: border-box;
		display: flex;
		word-break: break-all;
		align-items: center;
		justify-content: center;
	}

	.action {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin-top: 20rpx;

		.action-item {
			width: 20%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-between;

			text {
				margin-top: 10rpx;
				font-size: $cl-font-size-base
			}
		}
	}

	.home {
		padding: 20rpx;
		display: flex;
		overflow: auto;
		height: auto;
		flex-direction: column;
		// justify-content: space-around;
		box-sizing: border-box;
	}

	.view-button {
		background-color: $cl-color-imagePlayer-primary;
		border-radius: 0 0 20rpx 20rpx;
		display: flex;
		justify-content: space-around;
		color: #fff;
	}

	.button-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.button-list {
		padding: 20rpx 0;
		flex: 1;
		text-align: center;
		display: flex;
		align-items: center;
	}

	.button-title {
		font-size: $cl-font-size-title;
		margin-top: 6rpx;
		white-space: pre-wrap;
		margin-left: 20rpx;
	}
</style>